#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/11 10:00
    Desc  :
--------------------------------------
"""
import json
import time

from flask import request

from application import app, mongo
from common.libs.JsonResponseUtils import JsonResponse
from common.libs.JwtUtils import verify_jwt
from config.base import NOT_TOKEN_URL
from servers.models.logModel import Log


@app.before_request
def request_process():
    app.logger.info(f'*******************************请求开始*******************************')
    global startTime
    global logData
    startTime = round(time.time() * 1000, 0)
    app.logger.info(f'开始时间 -- {startTime}')
    app.logger.info(f'请求路径 -- {request.path}')
    app.logger.info(f'请求地址 -- {request.remote_addr}')
    app.logger.info(f'请求方法 -- {request.method}')
    app.logger.info(f'请求参数 -- {request.json}')
    logData = {
        'startTime': startTime,
        'remote_addr': request.remote_addr,
        'path': request.path,
        'method': request.method,
        'params': request.json,
        'headers': request.headers,
    }

    if request.path in NOT_TOKEN_URL:
        return None

    accesstoken = request.headers.get('accesstoken')

    if accesstoken is None or accesstoken == '' or verify_jwt(accesstoken) is None:
        return JsonResponse(code = 40004, data = None, message = "accesstoken失效").jsonExit()
    logData['username'] = verify_jwt(accesstoken).get('username')


@app.after_request
def response_process(response):
    try:
        endTime = round(time.time() * 1000, 0)
        app.logger.info(f'结束时间 -- {endTime}')
        app.logger.info(f'请求耗时 -- {endTime - startTime}ms')
        # app.logger.info(f'请求耗时 -- {(endTime - startTime)}s')
        app.logger.info(f'响应结果 -- {str(json.dumps(response.json, ensure_ascii = False))}')
        logData['endTime'] = endTime
        logData['castTime'] = endTime - startTime
        logData['response'] = str(json.dumps(response.json))
        # app.logger.info(f'日志 -- {logData}')
        if '/admin/log' not in request.path:
            try:
                if request.method != 'OPTIONS':
                    Log.objects().create(**logData)
            except Exception as e:
                app.logger.error(Exception(e))
        app.logger.info(f'*******************************请求结束*******************************')
        return response
    except Exception as e:
        app.logger.error(e)
        return JsonResponse(code = 50000, data = None, message = "系统异常", errors = f'{e}').jsonExit()
